package org.example.library.dao;

import org.example.library.util.JDBCutils;
import org.example.library.vertile.User;

import java.sql.*;


public class UserDao {

    PreparedStatement ps = null;
    ResultSet rs = null;
    Connection connection = null;
    JDBCutils jdbCutils = new JDBCutils();

    public int addUser(String username,String password){
        int count = 0;
        try{
            connection = JDBCutils.getconnection();
            String sql = "INSERT INTO tb_user (username,password) VALUE (?,?)";
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            count = ps.executeUpdate();
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            JDBCutils.release(rs,ps,connection);
        }
        return count;
    }

    public int updateUser(String username,String password){
        int count = 0;
        try{
            connection = JDBCutils.getconnection();
            String sql = "UPDATE FROM tb_user SET password=? WHERE username=?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,password);
            ps.setString(2,username);
            count = ps.executeUpdate();
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            JDBCutils.release(rs,ps,connection);
            return count;
        }
    }

    public User queryUser(String username){
        User user = new User();
        try{
            connection = JDBCutils.getconnection();
            String sql = "SELECT * FROM tb_user WHERE username=?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();
            if(rs.next()){
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            JDBCutils.release(rs,ps,connection);

        }
        return user;
    }

    public boolean isExistUser(String username){
        return queryUser(username) != null;
    }
}
